package com.association.main.frontcontroller;

import com.association.main.common.R;
import com.association.main.domain.*;
import com.association.main.dto.ClubsDto;
import com.association.main.service.*;
import com.association.main.utils.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/front")
@Slf4j
public class ClubController {
    @Autowired
    private ClubsService clubsService;

    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private UsersService usersService;

    @Autowired
    private JoinInfoService joinInfoService;


    @Autowired
    private ApplyJoinService applyJoinService;

    @GetMapping("/clubs/list")
    public R<Page> clubsList(int page) {
        Page pageInfo = new Page(page, 10);
        LambdaQueryWrapper<Clubs> clubsLambdaQueryWrapper=new LambdaQueryWrapper<>();
        clubsLambdaQueryWrapper.select(
                Clubs::getId,
                Clubs::getName,
                Clubs::getDescription,
                Clubs::getIsApply,
                Clubs::getCreatedBy,
                Clubs::getDepartmentId,
                Clubs::getLogo
        );
        List<Clubs> list = clubsService.list(clubsLambdaQueryWrapper);
        List<ClubsDto> ClubsDtoList = list.stream().map((item) -> {
            Users users = usersService.getById(item.getCreatedBy());
            Department department = departmentService.getById(item.getDepartmentId());
            LambdaQueryWrapper<JoinInfo> joinInfoLambdaQueryWrapper1=new LambdaQueryWrapper<>();
            joinInfoLambdaQueryWrapper1.eq(JoinInfo::getClubId,item.getId());
            int count = joinInfoService.count(joinInfoLambdaQueryWrapper1);
            ClubsDto clubsDto=new ClubsDto(department.getName(),null, null,null,count);
            BeanUtils.copyProperties(item, clubsDto);
            return clubsDto;
        }).collect(Collectors.toList());
        pageInfo.setRecords(ClubsDtoList);
        return R.success(pageInfo);
    }

    @GetMapping("/clubs/getById")
    public R<ClubsDto> getClubById( int id) {
        LambdaQueryWrapper<Clubs> clubsLambdaQueryWrapper=new LambdaQueryWrapper<>();
        clubsLambdaQueryWrapper.eq(Clubs::getId,id);
        clubsLambdaQueryWrapper.select(
                Clubs::getId,
                Clubs::getName,
                Clubs::getDescription,
                Clubs::getIsApply,
                Clubs::getCreatedBy,
                Clubs::getDepartmentId,
                Clubs::getLogo,
                Clubs::getCreatedAt
        );
        Clubs clubs = clubsService.getOne(clubsLambdaQueryWrapper);
        if (clubs == null) {
            return R.error("社团不存在");
        }
        Users users = usersService.getById(clubs.getCreatedBy());
        Department department = departmentService.getById(clubs.getDepartmentId());
        LambdaQueryWrapper<JoinInfo> joinInfoLambdaQueryWrapper1=new LambdaQueryWrapper<>();
        joinInfoLambdaQueryWrapper1.eq(JoinInfo::getClubId,clubs.getId());
        int count = joinInfoService.count(joinInfoLambdaQueryWrapper1);
        ClubsDto clubsDto=new ClubsDto(department.getName(),users.getName(), users.getPhone(),users.getEmail(),count);
        BeanUtils.copyProperties(clubs, clubsDto);
        return R.success(clubsDto);
    }


        @GetMapping("/clubs/mylist")
    public R<Page> clubsList(int page, HttpServletRequest request) {
            Page<ClubsDto> pageInfo = new Page<>(page, 10);
            String token = request.getHeader("token");
            Integer userId = JwtUtil.getUserId(token);

            // 构造查询条件
            LambdaQueryWrapper<JoinInfo> joinInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            joinInfoLambdaQueryWrapper.eq(JoinInfo::getMemberId, userId);

            // 获取用户参与列表
            List<JoinInfo> joinInfoList = joinInfoService.list(joinInfoLambdaQueryWrapper);
            if(joinInfoList.size()>0){
                List<Integer> joinClubIds = joinInfoList.stream().map(JoinInfo::getClubId).collect(Collectors.toList());

                // 构造查询条件
                LambdaQueryWrapper<Clubs> clubsLambdaQueryWrapper = new LambdaQueryWrapper<>();
                clubsLambdaQueryWrapper.in(Clubs::getId, joinClubIds);
                clubsLambdaQueryWrapper.select(
                        Clubs::getId,
                        Clubs::getName,
                        Clubs::getDescription,
                        Clubs::getIsApply,
                        Clubs::getCreatedBy,
                        Clubs::getDepartmentId,
                        Clubs::getLogo,
                        Clubs::getCreatedAt
                );
                // 获取用户参与的社团列表
                List<Clubs> clubsList = clubsService.list(clubsLambdaQueryWrapper);

                // 将社团列表转换为社团 DTO 列表
                List<ClubsDto> clubsDtoList = clubsList.stream().map(clubs -> {


                    Users users = usersService.getById(clubs.getCreatedBy());
                    Department department = departmentService.getById(clubs.getDepartmentId());
                    LambdaQueryWrapper<JoinInfo> joinInfoLambdaQueryWrapper1=new LambdaQueryWrapper<>();
                    joinInfoLambdaQueryWrapper1.eq(JoinInfo::getClubId,clubs.getId());
                    int count = joinInfoService.count(joinInfoLambdaQueryWrapper1);
                    ClubsDto clubsDto=new ClubsDto(department.getName(),users.getName(), users.getPhone(),users.getEmail(),count);
                    BeanUtils.copyProperties(clubs, clubsDto);
                    return clubsDto;
                }).collect(Collectors.toList());


                pageInfo.setRecords(clubsDtoList);
            }

            return R.success(pageInfo);
        }


   @PostMapping("/clubs/apply")
    private R<String> apply(@RequestBody ApplyJoin applyJoin, HttpServletRequest request){
       String token = request.getHeader("token");
       Integer userId = JwtUtil.getUserId(token);
       //获取用户ID
       LambdaQueryWrapper<ApplyJoin> applyJoinLambdaQueryWrapper=new LambdaQueryWrapper<>();
       applyJoinLambdaQueryWrapper.eq(ApplyJoin::getClubId,applyJoin.getClubId());
       applyJoinLambdaQueryWrapper.eq(ApplyJoin::getMemberId,userId);
       applyJoinLambdaQueryWrapper.in(ApplyJoin::getStatus, new int[]{1, 0});
       ApplyJoin applyJoin1 = applyJoinService.getOne(applyJoinLambdaQueryWrapper);
       if(applyJoin1==null){
           //参数加工
           ApplyJoin applyJoin2=new ApplyJoin();
           applyJoin2.setClubId(applyJoin.getClubId());//传参
           applyJoin2.setMemberId(userId);
           applyJoin2.setCreateTime(LocalDateTime.now());
           applyJoin2.setText(applyJoin.getText());//传参
           applyJoin2.setUpdateTime(LocalDateTime.now());
           applyJoin2.setWords(applyJoin.getWords());//传参
           applyJoinService.save(applyJoin2);
           return R.success("申请成功，请等待审核");
       }else{
           return R.error("已经申请过了");
       }
   }


    @GetMapping("/clubs/isClub")
    public R<String> isJoinedClub(Integer clubId, HttpServletRequest request) {
        String token = request.getHeader("token");
        Integer userId = JwtUtil.getUserId(token);

        LambdaQueryWrapper<JoinInfo> joinInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        joinInfoLambdaQueryWrapper.eq(JoinInfo::getMemberId, userId);
        joinInfoLambdaQueryWrapper.eq(JoinInfo::getClubId,clubId);

        // 获取用户参与列表
        int count = joinInfoService.count(joinInfoLambdaQueryWrapper);
        if(count<=0){
         return R.success("no");
     }else{
         return R.success("yes");
     }

    }




}
